﻿using SBSimpleSftp;
using SBSSHKeyStorage;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SBB.WinForms.SFTP.TestClient
{
    public partial class Form1 : Form
    {
        private TElSimpleSFTPClient _sftpClient = null;

        private Stream _file;

        public Form1()
        {
            InitializeComponent();

            SBUtils.Unit.SetLicenseKey("123A2EB227B191D0CCF215E707E9986BA63E23CB933F86547907FE2B26F2B05AAAA35C5DDD78628DE584D2BD34293FC8D99D48C6E5E63172813AAD1CBC07CEE7DBAB2E316C4548B166FBC8689C867CEABD61175494B039F15AE38A1A0C5AF9895624B45E396882C8B096F07B4163292C2ADFEC96CDCC814C900665BB0D0CCC083BCB68252BDE4C4C818E7AE14C5A897995C445D3CA4780858D7AF8F9E5218A4CB7431279293E39FA84820C09B740C5BE7A96B4DCEF8E03E53CC62C33D6D91A7750A55DF364B0A1DD36A0405D0E3EA9AED176B1DE3FDFC5837CDE346AC9065FF0D30351D85D6021A2834367BD74D5447D355EFDF3290F18B056E2CE43D3FDAB89");

            _sftpClient = new TElSimpleSFTPClient();
            _sftpClient.Address = "127.0.0.1";
            _sftpClient.Port = 8733;

            _sftpClient.AuthenticationTypes = SBSSHConstants.Unit.SSH_AUTH_TYPE_PASSWORD;

            _sftpClient.Username = "TestUser";

            _sftpClient.OnKeyValidate += new SBSSHCommon.TSSHKeyValidateEvent(onKeyValidate);
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                _file = fileDialog.OpenFile();

                fileStatus.Text = "File select. Press Send to transfer file to server";
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            fileStatus.Text = "Transferring file...";

            using (var sbbServer = new SBBServer.SFTPServiceClient()) {
                sbbServer.Start();

                _sftpClient.Open();

                _sftpClient.UploadStream(_file, Path.GetFileName(fileDialog.FileName), SBTypes.TSBFileTransferMode.ftmOverwrite);

                fileStatus.Text = "File transfer successful!";
            }
        }

        private void onKeyValidate(object sender, TElSSHKey key, ref bool isValid)
        {
            //TODO: Implement proper key validation here
            isValid = true;
        }
    }
}
